package com.ruoyi.web.controller.WX;


import com.ruoyi.common.constant.ConstantsOkr;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.MakeOrderNumUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/WX")
public class WXController extends BaseController {

    private SysUser user;

    @Autowired
    private IOkrInformService iOkrInformService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IOkrInfoService okrInfoService;
    private Long cycleId = 9L;
    private String rowId;
    @Autowired
    private IOkrCycleService okrCycleService;
    @Autowired
    private IOkrTaskService okrTaskService;
    @Autowired
    private IOkrCommentService okrCommentService;



    /**
     * 微信小程序登录页面
     * @param username
     * @param password
     * @param rememberMe
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            user= ShiroUtils.getSysUser();
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    /**
     * 通知
     * @return 通知列表
     */
    @ResponseBody
    @GetMapping("/inform")
    public List<OkrInform> informList(){
        List<OkrInform> okrInforms=iOkrInformService.selectInformByUserId(user.getUserId());
        Set<String>users=new HashSet<>();
        List<OkrInform> informs=new LinkedList<>();
        if (okrInforms.size()> 0){
            for (OkrInform okrInform:
                    okrInforms) {
                if (!users.contains(okrInform.getParentName())){
                    informs.add(okrInform);
                    users.add(okrInform.getParentName());
                }
            }
        }
        return informs;
    }

    /**
     * 通知详情页
     * @return 通知列表
     */
    @ResponseBody
    @PostMapping("/userInform")
    public List<OkrInform> informList(Long parentId){
        List<OkrInform> okrInforms=iOkrInformService.selectInformByUser(user.getUserId(),parentId);
        return okrInforms;
    }

    /**
     *
     * @return 获取当前用户信息
     */

    @ResponseBody
    @GetMapping("/user")
    public SysUser selectuser(){
        return user;
    }

    /**
     *
     * @return返回所有公司成员
     */
    @ResponseBody
    @GetMapping("/userList")
    public List<SysUser> userList(){
        List<SysUser>users=sysUserService.selectAllUser();
        return users;
    }

    /**
     *
     * @return OKR的object
     */
    @ResponseBody
    @PostMapping("/okr")
    public List<OkrInfo> okr(){
        List<OkrInfo> okrInfos=okrInfoService.selectOkrInfosById(this.cycleId,user.getUserId());
        return okrInfos;
    }

    /**
     *
     * @param userId
     * @return 同事OKR
     */
    @ResponseBody
    @PostMapping("/otherOkr")
    public List<OkrInfo> okr(Long userId){
        List<OkrInfo> okrInfos=okrInfoService.selectOkrInfosById(this.cycleId,userId);
        return okrInfos;
    }

    /**
     *
     * @param rowId
     * @param userId
     * @return 同事Kr
     */
    @ResponseBody
    @PostMapping("/otherKr")
    public List<OkrInfo> kr(String rowId,Long userId){
        List<OkrInfo> okrInfos=okrInfoService.selectOkrInfosById(cycleId,userId);
        List<OkrInfo> krs=new LinkedList<>();
        for (OkrInfo okr:
                okrInfos) {
            if (okr.getParentId().equals(rowId)&& okr.getCycleId().equals(this.cycleId)){
                krs.add(okr);
            }
        }
        return krs;
    }

    /**
     *
     * @param rowId
     * @return OKR的key
     */
    @ResponseBody
    @PostMapping("/okr-kr")
    public List<OkrInfo> kr(String rowId){
        List<OkrInfo> okrInfos=okrInfoService.selectOkrInfosById(cycleId,user.getUserId());
        List<OkrInfo> krs=new LinkedList<>();
        for (OkrInfo okr:
             okrInfos) {
            if (okr.getParentId().equals(rowId)&& okr.getCycleId().equals(this.cycleId)){
                krs.add(okr);
            }
        }
        return krs;
    }

    @ResponseBody
    @PostMapping("/cycle")
        public void setCycleId(Long cycleId){
        System.out.println(cycleId);
        this.cycleId= cycleId;
    }

    @ResponseBody
    @GetMapping("/cycle")
    public List<String> getCycleId(){
        List<OkrCycle> list = okrCycleService.selectOkrUseCycleList();
        List<String>cycleNames=new LinkedList<>();
        for (OkrCycle cycle:
             list) {
            cycleNames.add(cycle.getCycleName());
        }
        return cycleNames;
    }

    @ResponseBody
    @GetMapping("/task")
    public List<OkrTask> getTask(){
        OkrTask task= new OkrTask();
        task.setUserId(user.getUserId());
        List<OkrTask> tasks = okrTaskService.selectOkrTaskList(task);
        return tasks;
    }

    @ResponseBody
    @PostMapping ("/addOkr")
    public void addOkr(String okrs){
        String substring = okrs. substring(1, okrs.length() - 1);
        String[] split = substring. split(  "," );
        List<OkrInfo> okrInfos = new ArrayList<>();
        for (int i = split.length-1;i > 0;i -= 2){
            char type = split[i]. charAt(split[i].length() - 2);
            String objRowId = new MakeOrderNumUtil().makeOrderNum();
            String content = split[i-1]. substring(12,split[i-1].length() - 1);
            OkrInfo okrInfo= new OkrInfo();
            okrInfo.setContent(content);
            okrInfo.setRowType((long) type -48);
            okrInfo.setCycleId(cycleId);
            okrInfo.setUserId(user.getUserId());
            okrInfo.setRowId(objRowId);
            if (okrInfo.getRowType().equals((long)0)){
                rowId = objRowId;
            } else {
                okrInfo.setParentId(rowId);
            }
            okrInfoService.insertOkrInfo(okrInfo);
        }
    }

    @ResponseBody
    @PostMapping ("/editOkr")
    public void editOkr( Long id, String content, String confidenceStar, String scoreStar){
        OkrInfo  okrInfo= okrInfoService.selectOkrInfoById(id);
        okrInfo.setContent(content);
        okrInfo.setConfidenceStar(confidenceStar);
        okrInfo.setScoreStar(scoreStar);
        okrInfoService.updateOkrInfo(okrInfo);
    }

    @ResponseBody
    @GetMapping("countObject")
    public Integer countObject(){
        Integer count = okrInfoService.countOkr(cycleId,user.getUserId(), (long) 0);
        return count;
    }

    @ResponseBody
    @GetMapping("countKR")
    public Integer countKR(){
        Integer count = okrInfoService.countOkr(cycleId,user.getUserId(), (long) 1);
        return count;
    }

    @ResponseBody
    @GetMapping("remainTime")
    public Integer remainTime()throws Exception{
        System.out.println(cycleId);
        String endTime = okrCycleService.selectOkrCycleById(cycleId).getEndTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//yyyy-mm-dd, 会出现时间不对, 因为小写的mm是代表: 秒
        Date utilDate = sdf.parse(endTime);
        Date date = new java.sql.Date(utilDate.getTime());
        Date date1 =  new Date();
        int remainTime = (int) ((date.getTime()-date1.getTime())/(1000*3600*24));
        return remainTime;
    }

    @ResponseBody
    @GetMapping("countType1")
    public Integer countType1(){
        Integer count = okrInfoService.countOkrByWorkStatus(cycleId, user.getUserId(), (long) 1);
        System.out.println(cycleId);
        return count;
    }

    @ResponseBody
    @GetMapping("countType2")
    public Integer countType2(){
        Integer count = okrInfoService.countOkrByWorkStatus(cycleId, user.getUserId(), (long) 2);
        return count;
    }

    @ResponseBody
    @GetMapping("countType3")
    public Integer countType3(){
        Integer count = okrInfoService.countOkrByWorkStatus(cycleId, user.getUserId(), (long) 3);
        return count;
    }

    @ResponseBody
    @PostMapping("comment")
    public List<OkrComment> comments(Long okrId){
        OkrComment comment = new OkrComment();
        comment.setObjectId(okrId);
        System.out.println(okrId);
        List<OkrComment> comments = okrCommentService.selectOkrCommentList(comment);
        for (OkrComment okrComment:
             comments) {
            String string=okrComment.getContent();
            string = string.replaceAll("<br/>|&lt;|&gt;", "");
            Long userId = okrComment.getUserId();
            okrComment.setAvatar(sysUserService.selectUserById(userId).getAvatar());
            okrComment.setUserName(sysUserService.selectUserById(userId).getUserName());
            okrComment.setContent(string);
        }
        return comments;
    }

    @ResponseBody
    @PostMapping("addComment")
    public void addComment(String content,Long objectId){
        OkrComment comment = new OkrComment();
        comment.setContent(content);
        comment.setObjectId(objectId);
        comment.setStatus(ConstantsOkr.COMMENT_DEFAULT_STATES);
        comment.setUserId(user.getUserId());
        comment.setAddTime(DateUtils.getNowDate());
        comment.setUserIp(IpUtils.getIpAddr(getRequest()));
        okrCommentService.insertOkrComment(comment);
    }

}
